package com.mazong.serverescc.controller;

import com.mazong.serverescc.mapper.MyElasticSearchRepository;
import com.mazong.serverescc.pojo.TbArticle;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class EsController {

    @Autowired
    MyElasticSearchRepository elasticRepository;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    //--增加
    @RequestMapping(value = "/add")
    public String add() {
        //--1
        elasticsearchRestTemplate.createIndex(TbArticle.class);

        //--2
        List<TbArticle> list = new ArrayList<>();
        list.add(new TbArticle(1L, "宋词", "听雨", "少年听雨歌楼上，红烛昏罗帐。", 1));
        list.add(new TbArticle(2L, "宋词", "听雨", "壮年听雨客舟中，江阔云低、断雁叫西风。", 1));
        list.add(new TbArticle(3L, "宋词", "听雨", "而今听雨僧庐下，鬓已星星也。", 1));
        list.add(new TbArticle(4L, "宋词", "听雨", "悲欢离合总无情，一任阶前、点滴到天明。", 1));
        elasticRepository.saveAll(list);

        return "add ok";
    }

    //--查找
    @RequestMapping(value = "/find")
    public Object find(Long id) {
        return elasticRepository.findById(id);
    }

    //--显示全部
    @RequestMapping(value = "/all")
    public Object all() {
        return elasticRepository.findAll();
    }

    //--全文检索
    @RequestMapping(value = "/findText")
    public Object findText() {

        QueryStringQueryBuilder builder = new QueryStringQueryBuilder("悲欢");
        return elasticRepository.search(builder);
    }

    //--删除
    @RequestMapping(value = "/delete")
    public String delete(Long id) {
        elasticRepository.deleteById(id);
        return "delete ok";
    }

    //--修改
    @RequestMapping(value = "/update")
    public String update(Long id) {
        TbArticle article = new TbArticle(2L, "唐诗", "听雨", "自古逢秋悲寂寥，我言春日胜春朝。", 1);
        elasticRepository.save(article);

        return "update ok";
    }
}
